package com.atguigu.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.entity.Dict;
import com.atguigu.mapper.DictMapper;
import com.atguigu.service.DictService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:hx
 * @DateTime:2022/9/26 18:48
 * @Description:
 */
@DubboService
public class DictServiceImpl implements DictService {
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private JedisPool jedisPool;

    @Override
    public List<Map<String, Object>> findZnodes(Long parentId) {
        //子节点信息
        List<Dict> dictList = dictMapper.findZnodes(parentId);

        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (Dict dict : dictList) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id",dict.getId());
            map.put("name",dict.getName());
            //判断是否为父节点
            map.put("isParent",dictMapper.findCountByParentId(dict.getId()) > 0);
            list.add(map);
        }
        return list;
    }

    @Override
    public List<Dict> findDictListByParentDictCode(String DictCode) {
        //获取对象
        Jedis jedis = jedisPool.getResource();
        //拼接键
        String dictCodeKey = "shf:dict:dictCode:"+DictCode;

        String value = jedis.get(dictCodeKey);
        //判断
        if (!StringUtils.isEmpty(value)){
            jedis.close();
            return JSON.parseObject(value,List.class);
        }
        List<Dict> dictList = dictMapper.findDictListByParentDictCode(DictCode);
        if (!CollectionUtils.isEmpty(dictList)){
            jedis.set(dictCodeKey,JSON.toJSONString(dictList));
            jedis.close();
            return dictList;
        }
        return null;
    }

    @Override
    public List<Dict> findDictListByParentId(Long parentId) {
        Jedis jedis = jedisPool.getResource();
        String parentIdKey = "shf:dict:parentId:"+parentId;
        String value = jedis.get(parentIdKey);
        if (!StringUtils.isEmpty(value)){
            jedis.close();
            return JSON.parseObject(value,List.class);
        }
        List<Dict> dictListByParentId = dictMapper.findDictListByParentId(parentId);
        if (!CollectionUtils.isEmpty(dictListByParentId)){
            jedis.set(parentIdKey,JSON.toJSONString(dictListByParentId));
            jedis.close();
            return dictListByParentId;
        }
        return null;
    }
}
